class Solution
{
public:
    vector<vector<int>> threeSum(vector<int>& nums)
    {
        sort(nums.begin(), nums.end());
        vector<vector<int>> ans;
        int len = nums.size();
        int i = 0;
        while (i < len - 2)
        {
            if (nums[i] > 0) break;
            int left = i + 1;
            int right = len - 1;
            while (left < right)
            {
                int sum = nums[left] + nums[right];
                if (sum < -nums[i]) left++;
                else if (sum > -nums[i]) right--;
                else {
                    ans.push_back({ nums[i], nums[left], nums[right] });
                    left++, right--;
                    while (left < right && nums[left] == nums[left - 1]) left++;
                    while (left < right && nums[right] == nums[right + 1]) right--;
                }
            }
            i++;
            while (i < len - 2 && nums[i] == nums[i - 1]) i++;
        }
        return ans;
    }
};